package com.cfs.svcimpl.sys;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jettison.json.JSONObject;

import com.cfs.svc.sys.UploadService;
import com.cfs.po.Exp;
import com.cfs.po.sys.FileUploadVo;
import com.cfs.po.sys.GenRes;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class UploadServiceImpl implements UploadService {

	@Context
	private ServletContext cxt;
	private boolean nameRetain = false;
	private String URI = "/upload/";
	private String PATH = null;

	public boolean isNameRetain() {
		return nameRetain;
	}

	public void setNameRetain(boolean nameRetain) {
		this.nameRetain = nameRetain;
	}

	public String getPATH() {
		return PATH;
	}

	public void setPATH(String pATH) {
		PATH = pATH;
	}

	public String getURI() {
		return URI;
	}

	public void setURI(String uRI) {
		URI = uRI;
	}

	/**
	 * 上传文件
	 */
	@Override
	public FileUploadVo upLoad(HttpServletRequest request) {

		List<FileUploadVo> fList = new ArrayList<FileUploadVo>();
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		PATH = PATH==null ? cxt.getRealPath( URI ) : PATH;

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> list = upload.parseRequest(request);
			String path = PATH.endsWith(File.separator) ? PATH : (PATH + File.separator);
			String uri = cxt.getContextPath() + URI;
			Map<String, String> formMap = new HashMap<String, String>();
			for (int i = 0; i < list.size(); i++) {
				FileItem fi = list.get(i);

				if (fi.isFormField() ) {
					String formName = fi.getFieldName();
					String value = fi.getString();
					formMap.put(formName, value);

					if("PATH".equalsIgnoreCase(formName)){
						path = PATH + value.replaceAll("\\/\\/", "\\/");
						uri += value;
					}
				}
			}

			// CHECK 4 DIR
			File dir = new File(path);
			if (dir.isDirectory()) {
			} else if ( ( !dir.exists() || dir.isFile() ) && dir.mkdirs()) {
			} else {
				throw new Exception("文件不能上传至特定位置: " + path);
			}

			// SAVE FILE
			for (int i = 0; i < list.size(); i++) {
				FileItem fileItem = list.get(i);
				if (fileItem.isFormField()) {
				} else {
					// 使用原文件名，可以使用随机名称或UUDI
					String name = fileItem.getName();
					System.out.println("FILENAME:\r\n" + name);
					if(name!=null && !name.equals("")){
						if(nameRetain){
							int x = name.lastIndexOf("\\") + 1;
							int y = name.lastIndexOf("/") + 1;
							name = name.substring( x>y ? x : y);
						}else
							name = UUID.randomUUID().toString() + 
								name.substring(name.lastIndexOf('.'));
						File f = new File(path + File.separator + name);
						fileItem.write(f);

						FileUploadVo fuv = new FileUploadVo();
						fuv.setPath(f.getPath());
						fuv.setUri(uri + (uri.endsWith("/")?"":"/") + f.getName());
						fList.add(fuv);
					}
				}
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return fList.size()>0 ? fList.get(0) : null;
	}

	@Override
	public String upLoad4ie(HttpServletRequest request) {
		FileUploadVo vo = upLoad(request);

		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationInclusion(Include.NON_NULL);
		String str = "{}";
		try {
			str = mapper.writeValueAsString(vo);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return str;
	}

}
